源码系列

String

1
2
3
4
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
}

String 不可变的原因

  • String类被final修饰,不能被继承

  • 保存的是一个char型数组,而且是private修饰

    但可以通过反射进行修改。

    1
    2
    3
    4
    5
    6
    String str="hello";
    Class clazz=Class.forName("java.lang.String");
    Field field=clazz.getDeclaredField("value");
    field.setAccessible(true);

    char[] value=(char[]) field.get(str);

String.replace

其中String.replace(char,char)要比String.replaceAll(String,String)性能好,字符在200左右就能看出差异。但relpaceAll()方法支持正则表达式,会对参数进行解析。

public String substring(int beginIndex)方法

结束位置为文本末尾。

1
2
this.value = Arrays.copyOfRange(value, offset, offset+count)
//从字符数组进行一段范围的拷贝

重写equals方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public boolean equals(Object anObject) {
//先判断内存地址是否相同
if (this == anObject) {
return true;
}
//判断比较的对象是否是String类型
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}

Long

byte 1字节

short 2字节

int 4字节

long 8字节

switch中不能使用long型数据,因为跳转表值的存储空间一般为32位,很难容纳下long。而String可以通过hashcode()方法转换为整数。

缓存

内部实现了一种缓存机制,缓存了从-128到127内的所有long值。

1
2
3
4
5
6
7
8
9
10
11
 private static class LongCache {
private LongCache(){}

static final Long cache[] = new Long[-(-128) + 127 + 1];
//当容器初始化时,static修饰的代码块自动进行随之加载
static {
//缓存long值。
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}

工具类

通用特征

  • 构造器必须私有,使用时无须初始化

  • 工具类的工具方法必须被static和final来修饰,保证方法不可变

    Arrays.binarySearch() 用于快速从数组中查找出对应的值

0%